﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using zqdn.Models.Case;
using zqdn.Models.Apply;
using zqdn.Services.Interfaces.Case;
using zqdn.Web.App_Start;
using zqdn.Web.ViewModels;
using zqdn.Web.Filters;
using zqdn.Services.Auth;

namespace zqdn.Web.Controllers
{

    public class CaseController : Controller
    {
        private readonly ICaseService _icaserepository;
        private readonly IUserService _userService;

        public CaseController(IUserService userService, ICaseService icaserepository)
        {
            this._icaserepository = icaserepository;
            this._userService = userService;
        }

        public JsonResult List(string title)
        {
            try
            {
                //if (SessionContext.CurrentUser == null)
                //{
                //    return Json(new { Result = "100002", msg = "尚未注册，请先注册" }, JsonRequestBehavior.AllowGet);
                //}
                var articlelist = _icaserepository.getAllCase(title);
                var _result = Json(articlelist, JsonRequestBehavior.AllowGet);
                return _result;
            }
            catch (Exception ex)
            {
                return Json(new { Result = "error", msg = "服务异常" }, JsonRequestBehavior.AllowGet);
            }

        }


        public JsonResult Detail(int id)
        {
            try
            {
                //if (SessionContext.CurrentUser == null)
                //{
                //    return Json(new { Result = "100002", msg = "尚未注册，请先注册" }, JsonRequestBehavior.AllowGet);
                //}
                var article = _icaserepository.getCaseByID(id);
                var _result = Json(article, JsonRequestBehavior.AllowGet);
                return _result;
            }
            catch (Exception ex)
            {
                return Json(new { Result = "error", msg = "服务异常" }, JsonRequestBehavior.AllowGet);
            }

        }

        [HttpPost]
        public JsonResult addCase(CaseTplViewModel model)
        {
            try
            {
                //if (SessionContext.CurrentUser == null)
                //{
                //    return Json(new { Result = "100002", msg = "尚未注册，请先注册" });
                //}
                var re = _userService.GetUserByOprnID(model.OpenID);
                CaseTpl ctp = _icaserepository.getCaseByZyNo(model.ZyNo);
                if (ctp != null)
                {
                    return Json(new { Result = "error", msg = "该住院号相关病例已提交，无法重复提交" });
                }
                CaseTpl casetpl = new CaseTpl
                {
                    WriteTime = model.WriteTime,
                    Type = model.Type,
                    Name = model.Name,
                    ZyNo = model.ZyNo,
                    CNo = model.CNo,
                    Sex = model.Sex,
                    Age = model.Age,
                    DepNo = model.DepNo,
                    Weight = model.Weight,
                    Med_YDQ = model.Med_YDQ,
                    Med_WCQ = model.Med_WCQ,
                    Med_SXQ = model.Med_SXQ,
                    MedCom_YDQ = model.MedCom_YDQ,
                    MedCom_WCQ = model.MedCom_WCQ,
                    MedCom_SXQ = model.MedCom_SXQ,
                    CaseImg = model.CaseImg,
                    ActiveHos = model.ActiveHos,
                    ActiveID = model.ActiveID,
                    CreateUserID = re.ID,
                    Status = 0,
                    IsDeleted = false
                };
                _icaserepository.AddCase(casetpl);
                return Json(new { Result = "success", msg = "上传成功" });
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException ex)
            {
                string err = "";
                foreach (var validationErrors in ex.EntityValidationErrors)
                {
                    foreach (var validationError in validationErrors.ValidationErrors)
                    {
                        err += "Property: {0} throws Error: {1}" + "---" + validationError.PropertyName + "---" + validationError.ErrorMessage;
                    }
                }
                return Json(new { Result = "success", msg = err });
            }
        }

        [HttpPost]
        public JsonResult addCaseAfter(CaseAfterTplViewModel model)
        {
            try
            {
                //if (SessionContext.CurrentUser == null)
                //{
                //    return Json(new { Result = "100002", msg = "尚未注册，请先注册" });
                //}
                var re = _userService.GetUserByOprnID(model.OpenID);

                CaseTpl ctp = _icaserepository.getCaseByZyNo(model.ZyNo);
                if (ctp != null)
                {
                    return Json(new { Result = "error", msg = "该住院号相关病例已提交，无法重复提交" });
                }

                CaseTpl casetpl = new CaseTpl
                {
                    WriteTime = model.WriteTime,
                    Type = model.Type,
                    Name = model.Name,
                    ZyNo = model.ZyNo,
                    CNo = model.CNo,
                    Sex = model.Sex,
                    Age = model.Age,
                    DepNo = model.DepNo,
                    Weight = model.Weight,

                    MedCf_BTFN = model.MedCf_BTFN,
                    MedCf_YMTMD = model.MedCf_YMTMD,
                    Med_PW_1 = model.Med_PW_1,
                    Med_PW_2 = model.Med_PW_2,
                    Med_PW_3 = model.Med_PW_3,
                    Med_PW_4 = model.Med_PW_4,
                    MedCom_WCQ = "&",
                    MedCom_SXQ ="&",
                    MedCom_YDQ = "&",
                    Med_GZ = model.Med_GZ,
                    CreateUserID = re.ID,
                    IsDeleted = false,
                    CaseImg = model.CaseImg
                };
                _icaserepository.AddCase(casetpl);
                return Json(new { Result = "success", msg = "上传成功" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "error", msg = "上传失败" });
            }
        }



        [HttpPost]
        public JsonResult addApply(ApplyTplViewModel model)
        {
            try
            {
                if (SessionContext.CurrentUser == null)
                {
                    return Json(new { Result = "100002", msg = "尚未登录，请先登录" });
                }
                Apply applytpl = new Apply
                {
                    MetCity = model.MetCity,
                    SpeakCity = model.SpeakCity,
                    SpeakHos = model.SpeakHos,
                    SpeakDep = model.SpeakDep,
                    SpeakPost = model.SpeakPost,
                    SpeakPhone = model.SpeakPhone,
                    SpeakContent = model.SpeakContent,
                    SpeakTimePlan = model.SpeakTimePlan,
                    JoinCount = model.JoinCount,
                    SpeakRate = model.SpeakRate,
                    CreateUserID = SessionContext.CurrentUser.ID,
                    IsDeleted = false
                };
                _icaserepository.AddApply(applytpl);
                return Json(new { Result = "success", msg = "上传成功" });
            }
            catch (Exception ex)
            {
                return Json(new { Result = "error", msg = "上传失败" });
            }
        }


        #region 附件上传
        /// <summary>
        /// 上传资质证书
        /// </summary>
        /// <param name="imageUpLoad"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UploadCaseImg(HttpPostedFileBase imageUpLoad)
        {
            try
            {
                ///上传附件
                string upaddress = string.Empty;
                var c = Request.Files[0];
                if (c == null && c.ContentLength <= 0)
                {
                    return Json(new { Result = "error", msg = "服务异常" });
                }
                else
                {

                    string fileName = c.FileName;
                    string newFilename = DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(0, 9) + fileName.Substring(fileName.LastIndexOf('.'), fileName.Length - fileName.LastIndexOf('.'));

                    string savepath = "/Upload/" + DateTime.Now.Date.ToString("yyyy") + "/" + DateTime.Now.Date.ToString("MMdd");
                    string path = Server.MapPath("~") + savepath;

                    if (!System.IO.Directory.Exists(path))
                    {
                        System.IO.Directory.CreateDirectory(path);
                    }

                    try
                    {
                        c.SaveAs(path + "/" + newFilename);
                        upaddress += savepath + "/" + newFilename;

                        return Json(new { Result = "success", msg = "上传成功", uploadResult = upaddress });
                    }
                    catch (Exception ex)
                    {
                        return Json(new { Result = "error", msg = ex.ToString() });
                    }

                }
            }
            catch (Exception ex)
            {
                return Json(new { Result = "error", msg = ex.ToString() });
            }

        }
        #endregion
    }
}

        